package server;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @author: liufh
 * @create: 2021-10-12 11:15
 */
public class MyClassLoader extends ClassLoader {

//    //等于项目的根目录下的webapps目录下的具体项目路径
    private String path;

    public MyClassLoader(String path) {
        this.path = path;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        try {
            byte[] classbytes = null;
            classbytes = loadclassbytes(name);
            //定义类向JVM输入字节码文件
            Class<?> aClass = defineClass(name, classbytes, 0, classbytes.length);
            return aClass;
        } catch (IOException e) {
            throw new ClassNotFoundException(name);
        }
    }

    private byte[] loadclassbytes(String name) throws IOException {
        name = path + name;
        String cname = name.replace(".", "/") + ".class";//获取字节码文件名
        byte[] bytes = Files.readAllBytes(Paths.get(cname));
        return bytes;
    }

}
